package com.gogowan.agroenterprise.newview;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.NewCodeValidationRequest;
import com.gogowan.agroenterprise.model.NewCodeValidationResult;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.SalesPlaceDict;
import com.gogowan.agroenterprise.model.SellMaterialInfo;
import com.gogowan.agroenterprise.utils.SystemBroadCast;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * @author tjh
 * @功能描述 记录销售信息 并上传 步骤：先拍首尾码 得到批次列表以及每个批次所对应的产品名称， 用户只需填写销售信息。
 * @since 2017.7.30 添加拍新格式码
 */
public class NewSalesActivity extends BaseActivity implements OnClickListener {

	private ProgressDialog progressDialog;
	private EditText qsmEdit, jsmEdit;
	private EditText cpmcEdit, cpslEdit;
	private EditText xsryEdit, djhEdit;
	private TextView scrqText;
	private LinearLayout allLinear;
	private Spinner jxsSprinner;
	private List<String> jxsStrList = new ArrayList<String>();
	private ArrayAdapter<String> jxsAdapter;
	private String[] items = new String[] { "起始码", "结束码", "单据号" };
	// 起始码，结束吗
	private String startCode, endCode;
	private long enterpriseId;
	private long personId;
	private SalesPlaceDict[] salesplacedictArr;
	// 销售地编码
	private long salesplaceid;
	private boolean isNew;
	// 产品id
	private long selectedMaterialId;
	private int codeType = -1;
	private Dialog tipDialog;
	private String resultStr = "";

	private Handler myHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				qsmEdit.setFocusable(true);
				qsmEdit.setFocusableInTouchMode(true);
				qsmEdit.requestFocus();
				break;
			case 1:
				allLinear.setFocusable(true);
				allLinear.setFocusableInTouchMode(true);
				allLinear.requestFocus();
				break;
			case 2:
				jxsAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.new_sales_activity);
		initDialog();
		initView();
		initValue();
	}

	private void initDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);
		builder.setTitle("请选择扫码类型");
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					// 起始码
					String code = Utils.getCodeStr(resultStr);
					qsmEdit.setText(code);
					cpmcEdit.setText("");
					cpslEdit.setText("");
					jsmEdit.setText("");
					break;
				case 1:
					// 起始码
					if (Utils.isEmpty(qsmEdit.getText() + "")) {
						myHandler.sendEmptyMessage(0);
						showToast("请先扫描起始码");
					} else {
						String codes = Utils.getCodeStr(resultStr);
						jsmEdit.setText(codes);

						progressDialog = ProgressDialog.show(NewSalesActivity.this, "提示", "正在查询....", true, false);

						NewCodeValidationRequest request = new NewCodeValidationRequest();
						request.setBeginEWM(qsmEdit.getText() + "");
						request.setEndEWM(resultStr);
						request.setEnterpriseId(enterpriseId);

						NewCodeAsyn asyn = new NewCodeAsyn();
						asyn.execute(request);
					}
					break;
				case 2:
					// 单据号
					djhEdit.setText(resultStr);
					break;
				}

			}
		});
		tipDialog = builder.create();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		// 返回
		findViewById(R.id.new_sales_backBtn).setOnClickListener(this);
		// 扫描起始码
		findViewById(R.id.new_sales_smqsm_btn).setOnClickListener(this);
		// 扫描结束码
		findViewById(R.id.new_sales_smjsm_btn).setOnClickListener(this);
		// 扫描单据号
		findViewById(R.id.new_sales_djhsm_btn).setOnClickListener(this);
		// 保存提交
		findViewById(R.id.new_sales_bctj_btn).setOnClickListener(this);
		// 取消
		findViewById(R.id.new_sales_qx_btn).setOnClickListener(this);

		allLinear = (LinearLayout) findViewById(R.id.new_sales_linear);
		allLinear.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				myHandler.sendEmptyMessage(1);
				return false;
			}
		});

		qsmEdit = (EditText) findViewById(R.id.new_sales_qsm_edit);
		jsmEdit = (EditText) findViewById(R.id.new_sales_jsm_edit);
		jsmEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					if (Utils.isEmpty(qsmEdit.getText() + "")) {
						myHandler.sendEmptyMessage(0);
						showToast("请输入起始码");
					}
				} else {
					if ((!Utils.isEmpty(qsmEdit.getText() + ""))&&(!Utils.isEmpty(jsmEdit.getText() + ""))) {
						progressDialog = ProgressDialog.show(NewSalesActivity.this, "提示", "正在查询....", true, false);

						NewCodeValidationRequest request = new NewCodeValidationRequest();
						request.setBeginEWM(qsmEdit.getText() + "");
						request.setEndEWM(jsmEdit.getText() + "");
						request.setEnterpriseId(enterpriseId);

						NewCodeAsyn asyn = new NewCodeAsyn();
						asyn.execute(request);
					}
				}
			}
		});

		cpmcEdit = (EditText) findViewById(R.id.new_sales_cpmc_edit);
		cpslEdit = (EditText) findViewById(R.id.new_sales_cpsl_edit);
		xsryEdit = (EditText) findViewById(R.id.new_sales_xsry_edit);
		djhEdit = (EditText) findViewById(R.id.new_sales_djh_edit);
		scrqText = (TextView) findViewById(R.id.new_sales_scrq_text);
		scrqText.setOnClickListener(this);

		jxsSprinner = (Spinner) findViewById(R.id.new_sales_jxs_sprinner);
		// jxsAdapter = new ArrayAdapter<String>(this,
		// R.layout.simple_spinner_item, jxsStrList);
		// // 设置下拉列表的风格
		// jxsAdapter
		// .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		jxsAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item1, jxsStrList) {

			@Override
			public View getDropDownView(int position, View convertView, ViewGroup parent) {
				View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
				TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
				ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
				label.setText(jxsStrList.get(position));
				if (jxsSprinner.getSelectedItemPosition() == position) {
					check.setImageResource(R.drawable.invent_select);
					// viewHolder.selectBtn.setVisibility(View.GONE);
				} else {
					check.setImageResource(R.drawable.invent_noselect);
				}
				return view;
			}
		};
		jxsAdapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
		jxsSprinner.setAdapter(jxsAdapter);
		jxsSprinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				if (jxsStrList.size() != 0) {
					salesplaceid = salesplacedictArr[position].getSalesplaceid();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		initScanView(new SystemBroadCast.ScanResultListener() {
			@Override
			public void OnResult(String CodeString) {
				if (isVisible){
					resultStr=CodeString;
					// 生成单元
					if (tipDialog != null && !tipDialog.isShowing()) {
						tipDialog.show();
					}
				}
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {
		SharedPreferences preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		personId = preferences.getLong("personid", 0);
		isNew = preferences.getBoolean("isNew", false);
		xsryEdit.setText(MyApplication.mSettings.getString("username",""));
		jxsStrList.clear();
		if (salesplacedictArr == null || salesplacedictArr.length == 0) {
			jxsStrList.add("无销售经销商");
			jxsSprinner.setEnabled(false);
		} else {
			for (int i = 0; i < salesplacedictArr.length; i++) {
				jxsStrList.add(salesplacedictArr[i].getSalesplacename());
			}
			myHandler.sendEmptyMessage(2);
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.new_sales_backBtn:
			// 返回
			this.finish();
			break;
		case R.id.new_sales_smqsm_btn:
			// 扫描起始码
			Intent intent = new Intent(Intents.Scan.ACTION);
			startActivityForResult(intent, 100);
			break;
		case R.id.new_sales_smjsm_btn:
			// 扫描结束码
			if (Utils.isEmpty(qsmEdit.getText() + "")) {
				myHandler.sendEmptyMessage(0);
				showToast("请扫描起始码");
			} else {
				Intent intent2 = new Intent(Intents.Scan.ACTION);
				startActivityForResult(intent2, 101);
			}
			break;
		case R.id.new_sales_djhsm_btn:
			// 扫描单据号
			Intent intent3 = new Intent(Intents.Scan.ACTION);
			startActivityForResult(intent3, 102);
			break;
		case R.id.new_sales_scrq_text:
			// 生产日期选择
			ShowDateDialog("", new Handler.Callback() {

				@Override
				public boolean handleMessage(android.os.Message msg) {
					// TODO Auto-generated method stub
					scrqText.setText(msg.getData().getString("token"));
					return false;
				}
			});
			break;
		case R.id.new_sales_bctj_btn:
			// 保存提交
			if (Utils.isEmpty(qsmEdit.getText() + "")) {
				showToast("请输入或扫描起始码");
			} else if (Utils.isEmpty(jsmEdit.getText() + "")) {
				showToast("请输入或扫描结束码");
			} else if ((scrqText.getText() + "").equals("点击设置时间")) {
				showToast("请设置生产时间");
			}
			/*
			 * else if (Utils.isEmpty(djhEdit.getText() + "")) {
			 * showToast("请输入或扫描单据号"); }
			 */
			else {
				progressDialog = ProgressDialog.show(this, "提示", "正在保存....", true, false);

				SellMaterialInfo sellMaterialInfo = new SellMaterialInfo();
				sellMaterialInfo.setStartcode(qsmEdit.getText() + "");
				sellMaterialInfo.setEndcode(jsmEdit.getText() + "");
				sellMaterialInfo.setEnterpriseid(enterpriseId);
				sellMaterialInfo.setIsnew(isNew);

				sellMaterialInfo.setMaterialid(selectedMaterialId);
				sellMaterialInfo.setSalesplaceid(salesplaceid);
				sellMaterialInfo.setPersonid(personId);
				sellMaterialInfo.setType(codeType);
				sellMaterialInfo.setProductionTime(scrqText.getText() + "");
				sellMaterialInfo.setSaleOrderNum(djhEdit.getText() + "");

				SaveAsyn saveAsyn = new SaveAsyn();
				saveAsyn.execute(sellMaterialInfo);
			}
			break;
		case R.id.new_sales_qx_btn:
			// 取消
			this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 100) {
				// 起始码
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				String code = Utils.getCodeStr(contents);
				qsmEdit.setText(code);
				cpmcEdit.setText("");
				cpslEdit.setText("");
				jsmEdit.setText("");
			} else if (requestCode == 101) {
				// 结束码
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				String code = Utils.getCodeStr(contents);
				jsmEdit.setText(code);

				progressDialog = ProgressDialog.show(this, "提示", "正在查询....", true, false);

				NewCodeValidationRequest request = new NewCodeValidationRequest();
				request.setBeginEWM(qsmEdit.getText() + "");
				request.setEndEWM(contents);
				request.setEnterpriseId(enterpriseId);

				NewCodeAsyn asyn = new NewCodeAsyn();
				asyn.execute(request);
			} else if (requestCode == 102) {
				// 单据号
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				djhEdit.setText(contents);
			}
		}
	}

	/**
	 * 新码的请求批次
	 * 
	 * @author Administrator
	 */
	private class NewCodeAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			progressDialog.dismiss();
			if (res == null || res.equals("")) {
				Toast.makeText(NewSalesActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewSalesActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
				} else {
					NewCodeValidationResult resultInfo = (NewCodeValidationResult) Utils.fromJSON(string,
							NewCodeValidationResult.class);
					int result = resultInfo.getResult();
					if (result == 12010) {
						cpmcEdit.setText(resultInfo.getMaterialFullName());
						cpslEdit.setText(resultInfo.getCount() + "");
						selectedMaterialId = resultInfo.getMaterialId();
						codeType = resultInfo.getType();
					} else {
						cpmcEdit.setText("");
						cpslEdit.setText("");
						qsmEdit.setText("");
						jsmEdit.setText("");
						Toast.makeText(NewSalesActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			NewCodeValidationRequest request = (NewCodeValidationRequest) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(12000, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * @author tjh
	 * @功能 保存信息
	 */
	private class SaveAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			progressDialog.dismiss();
			if (res == null || res.equals("")) {
				Toast.makeText(NewSalesActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewSalesActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string, ResultInfo.class);
					if (resultInfo.getResult() == 4110) {
						Toast.makeText(NewSalesActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						NewSalesActivity.this.finish();
					} else {
						Toast.makeText(NewSalesActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			SellMaterialInfo sellMaterialInfo = (SellMaterialInfo) params[0];
			String json = Utils.toJSON(sellMaterialInfo);
			Message message = new Message(4100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}

	}

	@Override
	public void onResume() {
		isVisible = true;
		super.onResume();
		//registerReceiver(new String[] { getString(R.string.SCAN_ACTION) });
		registerIDataReceiver(new String[] { getString(R.string.SCAN_IDATA_ACTION) });
	}

	@Override
	protected void onPause() {
		isVisible = false;
		super.onPause();
	}

	@Override
	protected void handleReceiver(Context context, Intent intent) {
		super.handleReceiver(context, intent);
		if (isVisible) {
			if (getString(R.string.SCAN_ACTION).equals(intent.getAction())) {
				String scanStatus = intent.getStringExtra(getString(R.string.SCAN_STATE));
				if ("ok".equals(scanStatus)) {
					// 成功
					resultStr = intent.getStringExtra(getString(R.string.DATA_STRING)).trim();
					// 生成单元
					if (tipDialog != null && !tipDialog.isShowing()) {
						tipDialog.show();
					}

				} else {
					// 失败如超时等
					showToast(getString(R.string.scan_timeout_warn), 0);
				}
			}
		}
	}
	
	@Override
	protected void handleIDataReceiver(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.handleIDataReceiver(context, intent);
		if (isVisible) {
			if (getString(R.string.SCAN_IDATA_ACTION).equals(intent.getAction())) {
				String scanResult = intent.getStringExtra("value");
				if (scanResult.length() > 0) {
					resultStr = scanResult;
					// 生成单元
					if (tipDialog != null && !tipDialog.isShowing()) {
						tipDialog.show();
					}
				} else {
					// 失败如超时等
					showToast(getString(R.string.scan_timeout_warn), 0);
				}
			}
		}
	}

}